package me.dongcha.reggie402.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.dongcha.reggie402.common.R;
import me.dongcha.reggie402.utils.GuoYangYun;
import me.dongcha.reggie402.entity.User;
import me.dongcha.reggie402.utils.ValidateCodeUtils;
import me.dongcha.reggie402.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        GuoYangYun.sendMsg(phone, code);
        log.warn("[发送的验证码是]:{}", code);
//        session.setAttribute(phone, code);
        redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
//        String codeInSession = (String) session.getAttribute(phone);
        Object codeInRedis = redisTemplate.opsForValue().get(phone);
        if (codeInRedis == null || !codeInRedis.equals(code)) {
            return R.error("验证码验证失败");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("user", user.getId());
        redisTemplate.delete(phone);
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
